from rest_framework.generics import ListAPIView, ListCreateAPIView
from apps.users.models import User
from apps.meiduo_admin.serializers.user import UserListAPIViewSerialzer, UserCreateAPIViewSerializer
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from  apps.meiduo_admin.utils import PageNum
# # 自定义分页器
# class PageNum(PageNumberPagination):
#     page_size = 4
#     page_size_query_param = 'pagesize'
#     max_page_size = 10
#
#     def get_paginated_response(self, data):
#         return Response({
#             'count': self.page.paginator.count,
#             'lists': data, # 用户数据
#             'page': self.page.number,#当前页数
#             'pages': self.page.paginator.num_pages, # 总页数
#             'pagesize': self.page_size
#         })

    # 重写这个方法
    # def get_paginated_response(self, data):
    #     return Response(OrderedDict([
    #         ('count', self.page.paginator.count),
    #         ('next', self.get_next_link()),
    #         ('previous', self.get_previous_link()),
    #         ('results', data)
    #     ]))

# ListAPIView 视图可以进行查询操作但是不能进行添加的操作
# CreateAPIView 视图可以进行添加数据的操作
# ListCreateAPIView 二者的结合都可以进行实现
class UserListAPIView(ListCreateAPIView):

    pagination_class = PageNum
    # queryset = User.objects.all()
    # serializer_class = UserListAPIViewSerialzer 而如果想要实现添加的操作需要对序列化器进行选择，重写get_serializer_class方法
    def get_serializer_class(self):
        if self.request.method == 'GET':
            return UserListAPIViewSerialzer
        else:
            return UserCreateAPIViewSerializer

    # 指定查询数据(重写get_queryset方法)
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return User.objects.filter(username__contains=keyword)
        return User.objects.all()


